package cn.yuxiaoyuan.config;

import cn.hutool.core.util.IdUtil;
import cn.yuxiaoyuan.pojo.domain.Login;
import cn.yuxiaoyuan.service.ILoginService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * 容器的最后一步执行
 */
@Component
public class BootstrapListener implements ApplicationListener<ContextRefreshedEvent> {

//  第一个参数用户输入的密码  数据库保存的加密密码  返回true 密码正确  false 密码错误
//  passwordEncoder.matches()
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private ILoginService loginService;


	@Override
    public void onApplicationEvent(ContextRefreshedEvent event) {

        Login one = loginService.getOne(new LambdaQueryWrapper<Login>().eq(Login::getUsername, "admin"));
        if(one == null){
            getLogin();
        }
    }

    private void getLogin() {
        Login login = new Login();
        login.setId(IdUtil.createSnowflake(0L,0L).nextId());
        login.setUsername("admin");
        login.setPassword(passwordEncoder.encode("123456"));
        login.setType(0);
        login.setEnabled(true);
        login.setAdmin(true);
        login.setNickName("admin");
        login.setCreateTime(new Date());

        //给admin设置权限
        loginService.save(login);
    }
}